import { useState, useCallback, useRef } from 'react';
import { message } from 'antd';
import { BlackItem, getBlackList, searchStudents } from '@/utils/api/black/black';

interface UseBlackDataProps {
    pageSize: number;
}

export const useBlackData = ({ pageSize }: UseBlackDataProps) => {
    const [blacks, setBlacks] = useState<BlackItem[]>([]);
    const [total, setTotal] = useState<number>(0);
    const [pages, setPages] = useState<number>(0);
    const [loading, setLoading] = useState<boolean>(false);
    const [searchParams, setSearchParams] = useState<any>({});

    const abortControllerRef = useRef<AbortController | null>(null);

    // 获取黑名单列表
    const fetchBlacks = useCallback(async (pageNum: number = 1, pageSize: number = 10, params: any = {}) => {
        if (abortControllerRef.current) {
            abortControllerRef.current.abort();
        }

        const controller = new AbortController();
        abortControllerRef.current = controller;

        try {
            setLoading(true);

            const cleanedParams = { ...params };
            Object.keys(cleanedParams).forEach(key => {
                if (cleanedParams[key] === '' || cleanedParams[key] === undefined) {
                    delete cleanedParams[key];
                }
            });

            const hasSearchParams = Object.keys(params).length > 0;
            let response;

            if (hasSearchParams) {
                const requestData = {
                    pageNum: pageNum,
                    pageSize: pageSize,
                    ...params
                };
                response = await searchStudents(requestData, { signal: controller.signal });
            } else {
                const requestParams = {
                    pageNum: pageNum,
                    pageSize: pageSize,
                    ...params
                };
                response = await getBlackList(requestParams, { signal: controller.signal });
            }

            if (controller.signal.aborted) {
                return;
            }

            const data = response.data;
            setBlacks(data?.list ?? []);
            setTotal(data?.total ?? 0);
            setPages(data?.pages ?? 0);

            return {
                current: pageNum,
                pageSize
            };
        } catch (error: any) {
            if (error.name === 'AbortError') {
                console.log('请求被中止');
                return;
            }
            console.error('获取黑名单列表失败:', error);
            throw error;
        } finally {
            setLoading(false);
        }
    }, []);

    // 处理搜索
    const handleSearch = useCallback((params: any) => {
        const searchData = { ...params };

        Object.keys(searchData).forEach(key => {
            if (searchData[key] === undefined || searchData[key] === '') {
                delete searchData[key];
            }
        });

        setSearchParams(searchData);
        return fetchBlacks(1, pageSize, searchData);
    }, [fetchBlacks, pageSize]);

    // 处理重置
    const handleReset = useCallback(() => {
        setSearchParams({});
        return fetchBlacks(1, pageSize);
    }, [fetchBlacks, pageSize]);

    return {
        blacks,
        total,
        pages,
        loading,
        searchParams,
        fetchBlacks,
        handleSearch,
        handleReset,
        setLoading
    };
};